package com.laosg.spring.proxy.cglib;

import com.laosg.spring.proxy.User;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * <p>description: some thing </p>
 *
 * @author kevinruan@pano.im
 * @date 2020/6/23
 */
public class TestCglib {
    public static void main(String[] args) {
        //创建原始对象
        UserServiceImpl userService = new UserServiceImpl();
        //通过cglib 创建动态代理对象
        //实现方式不一样，但是也要classloader，设置父类，设置classbank(类似jdk proxy invocationHandler)
        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(TestCglib.class.getClassLoader());
        enhancer.setSuperclass(userService.getClass());
        MethodInterceptor methodInterceptor = new MethodInterceptor() {
            //等同于jdk proxy invocationHandler
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("-cglib log---");
                Object ret = method.invoke(userService, objects);
                return ret;
            }
        };
        enhancer.setCallback(methodInterceptor);
        UserServiceImpl us = (UserServiceImpl) enhancer.create();//创建对象
        us.register(new User());
    }
}
